package com.rzico.sbl.ui

import com.jeremyliao.liveeventbus.utils.observe
import com.lzy.okgo.model.HttpMethod
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityOpenBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.other.*
import com.rzico.sbl.ui.mine.InfoActivity
import com.rzico.sbl.ui.mine.ShopModifyActivity
import com.rzico.sbl.viewmodel.CommonViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.*
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.objectbox.equalString
import com.xinnuo.objectbox.getBox
import com.xinnuo.objectbox.getBoxEuery
import com.xinnuo.objectbox.model.AppLoginData
import com.xinnuo.objectbox.model.AppLoginData_
import com.xinnuo.objectbox.model.UserLoginData
import com.xinnuo.objectbox.model.UserLoginData_
import org.json.JSONObject

class OpenActivity : BaseActivity(R.layout.activity_open) {

    private val mBinding by lazy { ActivityOpenBinding.bind(getRootView()) }

    private lateinit var mShopId: String
    private lateinit var mShopStatus: String

    override fun getViewModel() = get<CommonViewModel>()

    override fun initData() {
        setToolbarVisibility(false)

        mShopId = getString("shopId")
        mShopStatus = getString("shopStatus")

        initView()
    }

    override fun initListener() {
        mBinding.apply {
            openImg.oneClick {
                (mShopId == "0" || mShopStatus == "failure")
                    .conditionElse(
                        actionTrue = {
                            startActivityEx<ShopModifyActivity>(
                                "title" to "添加店铺",
                                "status" to "open"
                            )
                        },
                        actionFalse = ::getShopStatus
                    )
            }

            openRight.oneClick { startActivityEx<InfoActivity>() }
        }

        observe<String>("shopOpen") {
            mShopId = it
            mShopStatus = "waiting"

            initView()
        }
    }

    private fun initView() {
        mBinding.apply {
            when {
                mShopStatus == "waiting" && mShopId != "0" -> {
                    openImg.setImageResource(R.mipmap.icon_open02)
                    openTitle.text = "审核中"
                    openText.text = "信息正在审核中\n请耐心等待"
                }
                mShopStatus == "failure" -> {
                    openImg.setImageResource(R.mipmap.icon_open01)
                    openTitle.text = "我要开店"
                    openText.text = "信息审核失败，请重新提交申请"
                }
            }
        }
    }

    /**
     * 获取店铺状态
     */
    private fun getShopStatus() {
        getViewModel()
            .request(
                requestUrl = BaseUrl.shop,
                requestMethod = HttpMethod.GET,
                onSuccess = {
                    val obj = JSONObject(it)

                    mShopId = obj.optNotEmpty("shopId", "0")
                    mShopStatus = obj.optNotNull("status")
                    val shopName = obj.optNotNull("shopName")
                    val expireDay = obj.optInt("expire", 365)
                    val privacy = obj.optNotEmpty("privacyStatus", "on")
                    val callStatus = obj.optNotNull("callOrder")
                    val canRob = obj.optBoolean("rob")
                    val isOpen = !obj.optBoolean("paused")
                    val isReal = obj.optBoolean("hasRealName")

                    putShared("shopId", mShopId)
                    putShared("shopName", shopName)
                    putShared("shopStatus", mShopStatus)
                    putShared("expireDay", expireDay)     //过期天数
                    putShared("privacyStatus", privacy)   //号码隐私保护
                    putShared("incomeStatus", callStatus) //手机来电接单
                    putShared("canRob", canRob)           //是否抢单
                    putShared("isOpen", isOpen)           //是否营业
                    putShared("isReal", isReal)           //是否实名

                    reportEnable = obj.optBoolean("phEnable")     //是否报货
                    driverEnable = obj.optBoolean("driverEnable") //是否纯司机

                    // 店铺时间配置
                    val objTimeStr = obj.optNotEmpty("shippingConfig", "{}")
                    val objTime = JSONObject(objTimeStr)
                    val orderWarn = objTime.optNotNull("orderOvertime")
                    putShared("configJson", objTimeStr) //店铺时间配置
                    putShared("orderWarn", orderWarn)   //订单超时时间

                    // 角色属性
                    val objRole = obj.optJSONObject("roles") ?: JSONObject()
                    userRole = objRole.optNotNull("id")
                    roleName = objRole.optNotNull("name")

                    // 服务商属性
                    val objOperate = obj.optJSONObject("operate") ?: JSONObject()
                    serviceId = objOperate.optNotNull("id")
                    serviceStep = objOperate.optNotNull("step")

                    // 保存用户信息
                    getBox<UserLoginData>()
                        .apply {
                            query()
                                .equalString(
                                    UserLoginData_.uid,
                                    getBoxEuery<AppLoginData>()
                                        .equal(AppLoginData_.isLogin, true)
                                        .build()
                                        .findFirst()
                                        ?.uid ?: ""
                                )
                                .build()
                                .findFirst()
                                ?.let { item ->
                                    item.shopId = mShopId
                                    item.shopName = shopName
                                    item.shopStatus = mShopStatus
                                    item.privacyStatus = privacy
                                    item.callTelStatus = callStatus.intValue
                                    item.canRob = canRob
                                    item.isOpen = isOpen
                                    item.isReal = isReal
                                    // 报货属性
                                    item.reportEnable = reportEnable
                                    item.driverEnable = driverEnable
                                    // 店铺时间配置
                                    item.expireDay = expireDay
                                    item.configJson = objTimeStr
                                    item.orderWarn = orderWarn
                                    // 角色属性
                                    item.userRole = objRole.optNotNull("id")
                                    item.roleName = objRole.optNotNull("name")
                                    // 服务商属性
                                    item.serviceId = objOperate.optNotNull("id")
                                    item.serviceStep = objOperate.optNotNull("step")

                                    put(item)
                                }
                        }

                    (mShopStatus == "success")
                        .conditionElse(
                            actionTrue = {
                                startActivityEx<MainActivity>()
                                finishView()
                            },
                            actionFalse = {
                                showToast("信息审核中，请耐心等待")
                            }
                        )
                }
            )
    }

}